<template>
  <el-form ref="deptForm" label-width="120px" :model="form" :rules="rules">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code" style="width:80%" placeholder="1-50个字符" />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width:80%" placeholder="请选择">
        <el-option v-for="item in employees" :key="item.id" :value="item.username" :label="item.username" />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input v-model="form.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { getEmployeeSimple } from '@/api/employees'
import { addDepartments, getDepartDetail, updateDepartments } from '@/api/departments'
export default {
  props: {
    pid: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    },
    originList: {
      type: Array,
      required: true
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      let list = []
      if (this.isEdit) {
        list = this.originList.filter(item => item.id !== this.pid).map(item => item.code)
        list.includes(value) ? callback(new Error('不许编码重复')) : callback()
      } else {
        list = this.originList.map(item => item.code)
        list.includes(value) ? callback(new Error('不许编码重复')) : callback()
      }
    }
    const validName = (rule, value, callback) => {
      // 先把所有儿子过滤过来用filter
      let list = null
      // console.log(list)
      if (this.isEdit) {
        const pid = this.originList.find(item => item.id === this.pid).pid
        list = this.originList.filter(item => item.pid === pid && item.id !== this.pid).map(item => item.name)
      } else {
        list = this.originList.filter(item => item.pid === this.pid).map(item => item.name)
      }
      list.includes(value) ? callback(new Error(value + '已存在')) : callback()
    }
    return {
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      employees: [],
      rules: {
        name: [
          { required: true, message: '请输入名字', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2-10位字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入编码', trigger: 'blur' },
          { min: 2, max: 10, message: '请输入2-10位字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ],
        manager: [
          { required: true, message: '请选择负责人', trigger: 'change' }
        ],
        introduce: [
          { required: true, message: '请输入简介', trigger: 'blur' },
          { min: 1, max: 300, message: '请输入1-300位字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadEmployee()
    this.loadDetail()
  },
  methods: {
    async loadEmployee() {
      try {
        const res = await getEmployeeSimple()
        // console.log(res)
        this.employees = res.data
      } catch (e) {
        console.log(e.message)
      }
    },
    async loadDetail() {
      if (!this.isEdit) return
      try {
        const res = await getDepartDetail(this.pid)
        console.log(res)
        this.form = res.data
      } catch (e) {
        console.log(e.message)
      }
    },
    hSubmit() {
      // 兜底校验，然后获得数据，成功则传递，失败则报错，用try{}catch（e）{e。message}
      this.$refs.deptForm.validate(async valid => {
        if (!valid) return
        let res = ''
        try {
          if (!this.isEdit) {
            res = await addDepartments({ ...this.form, pid: this.pid })
          } else {
            res = await updateDepartments(this.form)
          }
          console.log(res)
          this.$emit('success')
        } catch (e) { console.log(e.message) }
      })
    },
    hCancel() {
      this.$emit('close')
    }
  }

}
</script>

<style>

</style>
